﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Excel = Microsoft.Office.Interop.Excel;
using System.Text.Json;

namespace UDMBackService
{
    class Program
    {
        private static Mutex mutex;
        private const int Port = 54321;
        private static TcpListener listener;
        private static HttpListener _listener;
        static void Main(string[] args)
        {
            JudgeInstance();
            //AddListener();
            //StartHttpListener();
            //DoListen();
            //StartServer();
            StartService();
            // 1. 创建阻塞事件
            var waitHandle = new ManualResetEvent(false);

            // 2. 监听退出信号（如 Ctrl+C）
            Console.CancelKeyPress += (sender, e) =>
            {
                e.Cancel = true; // 防止进程直接终止
                waitHandle.Set(); // 释放事件，结束阻塞
            };

            // 3. 阻塞主线程，直到事件被触发
            waitHandle.WaitOne();
        }
        private static void JudgeInstance()
        {
            // 定义全局互斥量的名称
            string mutexName = "Global\\MySingleInstanceAppMutex";

            // 尝试创建互斥量
            bool createdNew;
            mutex = new Mutex(true, mutexName, out createdNew);

            if (!createdNew)
            {
                // 如果互斥量已经存在，说明已经有实例在运行
                Console.WriteLine("程序已经启动，不再启动新实例。");
                Environment.Exit(0);
            }
            // 释放互斥量
            mutex.ReleaseMutex();
        }
        static async void StartService()
        {
            var service = new HttpService();
            await service.StartAsync();
        }
        static async void StartServer()
        {
            listener = new TcpListener(IPAddress.Any, 54321);
            listener.Start();
            Console.WriteLine("服务已启动，等待客户端连接...");

            while (true)
            {
                TcpClient client = await listener.AcceptTcpClientAsync();
                HandleClient(client);
            }
        }

        static async void HandleClient(TcpClient client)
        {
            var stream = client.GetStream();
            byte[] buffer = new byte[1024];
            int bytesRead;
            string path = "";

            try
            {
                // 读取客户端发送的数据
                bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length);
                string request = Encoding.UTF8.GetString(buffer, 0, bytesRead);
                Console.WriteLine($"客户端请求: {request}");

                // 解析请求参数
                string[] parameters = request.Split('|');
                //if (parameters.Length != 2)
                //{
                //    SendResponse(client, "Error", "参数数量错误");
                //    return;
                //}

                //string param1 = parameters[0];
                //string param2 = parameters[1];

                // 处理请求
                //string result = ProcessRequest(param1, param2);
                
                if (parameters.Length == 2)
                {
                    //if (parameters[0].ToLower().Equals("pdf"))
                    {
                        path = ChangeToPDF(parameters[1]);
                    }
                }
                else if (parameters.Length == 4)
                {
                    //if (parameters[0].ToLower().Equals("pdf"))
                    {
                        path = ChangeToPDF(parameters[1], parameters[2], parameters[3]);
                    }
                }
                // 返回JSON格式的响应
                SendResponse(client, "success", path);
            }
            catch (Exception ex)
            {
                SendResponse(client, "fail", ex.Message);
            }
            finally
            {
                client.Close();
            }
        }

        static string ProcessRequest(string param1, string param2)
        {
            // 示例处理逻辑：将两个字符串拼接
            return $"处理结果：{param1} + {param2}";
        }

        static void SendResponse(TcpClient client, string status, string path)
        {
            var response = new
            {
                status = status,
                path = path
            };

            string jsonResponse = JsonConvert.SerializeObject(response);
            byte[] responseBytes = Encoding.UTF8.GetBytes(jsonResponse);

            client.GetStream().Write(responseBytes, 0, responseBytes.Length);
            Console.WriteLine($"发送响应: {jsonResponse}");
        }
        //private static void AddListener()
        //{
        //    try
        //    {
        //        // 启动服务
        //        tcpListener = new TcpListener(IPAddress.Any, 54321);
        //        tcpListener.Start();
        //        Thread listenerThread = new Thread(new ThreadStart(ListenForConnections));
        //        listenerThread.IsBackground = true;
        //        listenerThread.Start();
        //        //MessageBox.Show("监听启动");
        //    }
        //    catch (Exception ex)
        //    {
        //        //MessageBox.Show(ex.Message);
        //    }
        //}
        //private static void HandleClient(object obj)
        //{
        //    TcpClient client = (TcpClient)obj;
        //    NetworkStream stream = client.GetStream();
        //    byte[] buffer = new byte[1024];
        //    int bytesRead = stream.Read(buffer, 0, buffer.Length);
        //    string receivedData = System.Text.Encoding.UTF8.GetString(buffer, 0, bytesRead);

        //    // 处理接收到的参数
        //    string[] parameters = receivedData.Split(',');
        //    if (parameters.Length == 2)
        //    {
        //        string param1 = parameters[0];
        //        string param2 = parameters[1];
        //        //MessageBox.Show($"接收到参数: {param1}, {param2}");
        //    }
        //    else if (parameters.Length == 1)
        //    {
        //        string param1 = parameters[0];
        //        string messageBoxText = $"接收到参数: {param1}";
        //        //MessageBox.Show(messageBoxText);
        //        string path = ChangeToPDF(param1);
        //    }

        //    client.Close();
        //}
        //private static void ListenForConnections()
        //{
        //    while (true)
        //    {
        //        try
        //        {
        //            TcpClient client = tcpListener.AcceptTcpClient();
        //            Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClient));
        //            clientThread.IsBackground = true;
        //            clientThread.Start(client);
        //        }
        //        catch (Exception ex)
        //        {
        //            //MessageBox.Show("Error: " + ex.Message);
        //        }
        //    }
        //}
        private static string ChangeToPDF(string file)
        {
            string pdfFilePath = ""; // 替换为你想要保存的PDF文件路径
            string wbName;
            string pdfFolder;
            string sheetName = "";
            Excel.Application application;
            Excel.Workbook workbook = null;
            string tempFolder;

            try
            {
                //pdfFolder = foldPath + @"\pdf";
                //if (!Directory.Exists(pdfFolder))
                //{
                //    Directory.CreateDirectory(pdfFolder);
                //}
                application = new Excel.Application();
                // 打开Excel文件
                workbook = application.Workbooks.Open(file);
                // 获取第一个工作表
                //if (!string.IsNullOrEmpty(tbSheetName.Text.Trim()))
                //{
                //    sheetName = tbSheetName.Text.Trim();
                //}
                //else
                //{
                //    sheetName = ((Excel.Worksheet)workbook.Sheets[1]).Name;
                //}
                Excel.Worksheet worksheet = (Excel.Worksheet)workbook.Worksheets[1]; // 索引为1表示第一个工作表
                if (worksheet != null)
                {
                    //遍历行，看是否有行不能完整显示，调整行高
                    //ResizeRowHeight(workbook, worksheet);

                    wbName = workbook.Name.Split('.')[0];

                    tempFolder = System.IO.Path.GetTempPath() + Guid.NewGuid().ToString("N");
                    Directory.CreateDirectory(tempFolder);
                    pdfFilePath = tempFolder + @"\" + wbName + ".pdf";
                    //tempFolder = tempFolder + @"\" + "saveAsPDF.xlsx";
                    //workbook.SaveCopyAs(@"D:\testPDF.xlsx");
                    ////workbook.SaveCopyAs(tempFolder);
                    // 导出为PDF，第一个参数指定转出为PDF，还可以指定为XPS格式
                    worksheet.ExportAsFixedFormat(Excel.XlFixedFormatType.xlTypePDF, pdfFilePath, Excel.XlFixedFormatQuality.xlQualityStandard, false, false);
                    //report.pdf = pdfFilePath;
                    //report.result = "成功";
                }
                else
                {
                    //report.result = "失败";
                    //report.reason = "未找到名为“" + sheetName + "”的Sheet！";
                }
            }
            catch (Exception ex)
            {
                //report.result = "失败";
                //report.reason = ex.Message;
            }
            finally
            {
                if (workbook != null)
                {
                    workbook.Close(false);
                }
                //ExcelApp.App.ScreenUpdating = true;
            }
            return pdfFilePath;
            //reportList.Add(report);
        }
        private static string ChangeToPDF(string file, string sheetname, string output)
        {
            string pdfFilePath = ""; // 替换为你想要保存的PDF文件路径
            string wbName;
            string pdfFolder;
            string sheetName = "";
            Excel.Application application;
            Excel.Workbook workbook = null;
            string tempFolder;

            try
            {
                application = new Excel.Application();
                // 打开Excel文件
                workbook = application.Workbooks.Open(file);
                // 获取第一个工作表
                //Excel.Worksheet worksheet = (Excel.Worksheet)workbook.Worksheets[1]; // 索引为1表示第一个工作表
                Excel.Worksheet worksheet = (Excel.Worksheet)workbook.Worksheets[sheetname]; // 索引为1表示第一个工作表
                if (worksheet != null)
                {
                    wbName = workbook.Name.Split('.')[0];

                    pdfFilePath = output + @"\" + wbName + ".pdf";
                    ////workbook.SaveCopyAs(output);
                    // 导出为PDF，第一个参数指定转出为PDF，还可以指定为XPS格式
                    worksheet.ExportAsFixedFormat(Excel.XlFixedFormatType.xlTypePDF, pdfFilePath, Excel.XlFixedFormatQuality.xlQualityStandard, false, false);
                }
                else
                {
                    //report.result = "失败";
                    //report.reason = "未找到名为“" + sheetName + "”的Sheet！";
                }
            }
            catch (Exception ex)
            {
                //report.result = "失败";
                //report.reason = ex.Message;
            }
            finally
            {
                if (workbook != null)
                {
                    workbook.Close(false);
                }
                //ExcelApp.App.ScreenUpdating = true;
            }
            return pdfFilePath;
            //reportList.Add(report);
        }
        //private static void StartHttpListener()
        //{
        //    _listener = new HttpListener();
        //    _listener.Prefixes.Add("http://localhost:54321/");
        //    _listener.Start();

        //    // 启动一个线程来处理请求
        //    new System.Threading.Thread(() =>
        //    {
        //        while (_listener.IsListening)
        //        {
        //            try
        //            {
        //                HttpListenerContext context = _listener.GetContext();
        //                HandleRequest(context);
        //            }
        //            catch (Exception ex)
        //            {
        //                Console.WriteLine($"发生错误: {ex.Message}");
        //            }
        //        }
        //    }).Start();
        //}

        //private static void HandleRequest(HttpListenerContext context)
        //{
        //    // 获取请求参数
        //    string queryString = context.Request.Url.Query;
        //    string parameter = GetParameterFromQuery(queryString, "param");

        //    // 创建响应数据
        //    var responseData = new
        //    {
        //        Status = "Success",
        //        Result = parameter ?? "No parameter provided"
        //    };

        //    // 将响应数据序列化为JSON
        //    string jsonResponse = JsonConvert.SerializeObject(responseData);

        //    // 设置响应头
        //    context.Response.ContentType = "application/json";
        //    context.Response.ContentLength64 = Encoding.UTF8.GetByteCount(jsonResponse);

        //    // 写入响应内容
        //    using (var writer = new System.IO.StreamWriter(context.Response.OutputStream, Encoding.UTF8))
        //    {
        //        writer.Write(jsonResponse);
        //    }
        //}

        //private static void StopHttpListener()
        //{
        //    _listener.Stop();
        //    _listener.Close();
        //}

        //private static string GetParameterFromQuery(string queryString, string paramName)
        //{
        //    if (string.IsNullOrEmpty(queryString))
        //        return null;

        //    string[] pairs = queryString.TrimStart('?').Split('&');
        //    foreach (string pair in pairs)
        //    {
        //        string[] keyValue = pair.Split('=');
        //        if (keyValue.Length == 2 && keyValue[0] == paramName)
        //        {
        //            return keyValue[1];
        //        }
        //    }
        //    return null;
        //}
        //private async static void DoListen()
        //{
        //    var listener = new TcpListener(IPAddress.Any, Port);
        //    listener.Start();
        //    Console.WriteLine($"服务已启动，监听端口：{Port}");

        //    while (true)
        //    {
        //        var client = await listener.AcceptTcpClientAsync();
        //        _ = HandleClientAsync(client); // 异步处理客户端请求
        //    }
        //}
        //private static async Task HandleClientAsync(TcpClient client)
        //{
        //    using (client)
        //    using (var stream = client.GetStream())
        //    {
        //        byte[] buffer = new byte[1024];
        //        int bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length);
        //        string request = Encoding.UTF8.GetString(buffer, 0, bytesRead);

        //        // 解析参数（示例格式：param1|param2）
        //        string[] parameters = request.Split('|');
        //        var response = ProcessRequest(parameters);

        //        // 发送JSON响应
        //        string jsonResponse = System.Text.Json.JsonSerializer.Serialize(response);
        //        byte[] responseData = Encoding.UTF8.GetBytes(jsonResponse);
        //        await stream.WriteAsync(responseData, 0, responseData.Length);
        //    }
        //}

        //private static ResponseModel ProcessRequest(string[] parameters)
        //{
        //    if (parameters.Length != 2)
        //        return new ResponseModel { Status = "Error", Result = "参数数量错误" };

        //    try
        //    {
        //        // 业务逻辑处理（此处为示例）
        //        string combined = "simon";
        //        return new ResponseModel { Status = "Success", Result = combined };
        //    }
        //    catch
        //    {
        //        return new ResponseModel { Status = "Error", Result = "处理失败" };
        //    }
        //}
    }
    //public class ResponseModel
    //{
    //    public string Status { get; set; }
    //    public string Result { get; set; }
    //}
}
